import { AvatarDropdown, AvatarName, Footer, Question, SelectLang } from '@/components';
import { currentUser as queryCurrentUser } from '@/services/auth/api';
import { LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageLoading, SettingDrawer } from '@ant-design/pro-components';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history, Link } from '@umijs/max';
import React from 'react';
import defaultSettings from '../config/defaultSettings';
import { requestConfig } from './requestConfig';
import { ReLoginModal } from './components/ReLoginModal';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import relativeTime from 'dayjs/plugin/relativeTime';


// 扩展 Day.js 插件
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(relativeTime);

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const data = await queryCurrentUser({
        skipErrorHandler: true,
      });
      return data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}
const show_menus = (backendMenus: any, frontendRoutes: any) => {
  const validPaths = new Set<string>();

  // 递归收集所有path
  const collectPaths = (menus: any[]) => {
    if (!menus) {
      return [];
    }
    menus.forEach(menu => {
      if (menu.path) {
        validPaths.add(menu.path);
      }
      if (menu.children) {
        collectPaths(menu.children);
      }
    });
  };
  collectPaths(backendMenus);
  const filterRoutes = (routes: any[]): any[] => {
    return routes.filter(route => {
      // 如果路由有子路由，先过滤子路由
      if (route.routes || route.children) {
        const children = route.routes || route.children;
        const filteredChildren = filterRoutes(children);

        // 如果过滤后还有子路由，则保留该路由
        if (filteredChildren.length > 0) {
          if (route.routes) {
            route.routes = filteredChildren;
          }
          if (route.children) {
            route.children = filteredChildren;
          }
          return true;
        }
        // 如果没有子路由了，检查路由本身是否有权限
        return validPaths.has(route.path);
      }

      // 对于没有子路由的路由，直接检查path
      return validPaths.has(route.path);
    });
  };

  const menus = filterRoutes(frontendRoutes);
  // console.log(backendMenus);
  //  console.log(JSON.stringify(configMenus));
  return menus;
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    contentStyle: {
      paddingBlock: '6px',
      paddingInline: '6px',
    },
    actionsRender: () => [<Question key="doc" />, <SelectLang key="SelectLang" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar_url,
      // src: "avatar/1.jpg",
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown >{avatarChildren}</AvatarDropdown>;
      },
    },
    loading: false,
    // 页面水印
    // waterMarkProps: {
    //   content: initialState?.currentUser?.true_name,
    // },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
        <Link key="openapi" to="/docs" target="_blank">
          <LinkOutlined />
          <span>OpenAPI 文档</span>
        </Link>,
      ]
      : [],
    menu: {
      defaultOpenAll: false,
    },
    menuHeaderRender: undefined,
    postMenuData: (menus) => {
      const menus_filted = show_menus(initialState?.currentUser?.menus, menus)
      return menus_filted;
    },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          <ReLoginModal />

          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request: RequestConfig = {
  ...requestConfig,
};
